/****************************************************************************
**
** Copyright (C) 2012 Róbert Márki
**
** This file is part of Web Feeds.
**
** Web Feeds is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Web Feeds is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Web Feeds.  If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/

import QtQuick 1.1
import com.nokia.meego 1.0
import com.nokia.extras 1.1
import WebFeeds 1.0
import GoogleReader 1.0
import "../../../../shared/qml/UIConstants.js" as UIConstants
import "../../../../shared/qml" as Shared

Shared.CommonSheet {
    id: root
    signal itemsAdded
    property ListModel __model: ListModel {
        id: tagListModel
    }

    acceptButtonText: qsTr("Save")
    rejectButtonText: qsTr("Cancel")
    title: (root.pageItem.itemType == GoogleReaderItem.ItFeedItem) ?
               (root.pageItem.folders.length ? qsTr("Change folders") : qsTr("Add to folders"))
             : (root.pageItem.tags.length ? qsTr("Edit tags") : qsTr("Add tags"))
    property string failureText: (root.pageItem.itemType == GoogleReaderItem.ItFeedItem) ?
                                     (root.pageItem.folders.length ? qsTr("Failed to change folders") : qsTr("Failed to add to folders"))
                                   : (root.pageItem.tags.length ? qsTr("Failed to edit tags") : qsTr("Failed to add tags"))
    busyText: qsTr("Saving")
    onStatusChanged: {
        if((root.status == DialogStatus.Open)
                && (root.__model.count == 0)) {
            var itemTagList = (root.pageItem.itemType == GoogleReaderItem.ItFeedItem) ?
                        root.pageItem.folders : root.pageItem.tags;
            var tagList = root.pageItem.service.availableTags;
            for(var i = 0; i < tagList.length; ++i) {
                var tagId = tagList[i];
                var tagTextIndex = tagId.lastIndexOf("/");
                var tagText = tagId.substr(tagTextIndex + 1, tagId.length - tagTextIndex);
                root.__model.append({"title": tagText,
                                     "checked": (itemTagList.indexOf(tagId) >= 0)});
            }            
            root.itemsAdded();
        }
    }

    function addTag(tagText) {
        tagText = tagText.replace(/^\s+|\s+$/g, "");
        if(tagText.length) {
            for(var i = 0; i < tagListModel.count; ++i) {
                if(tagListModel.get(i).title == tagText) {
                    tagListModel.remove(i);
                    break;
                }
            }
            tagListModel.insert(0, {"title" : tagText, "checked": true});
            root.acceptButton.enabled = true;
            root.itemsAdded();
        }
    }

    onAccepted: {        
        root.busy = true;
        root.open();
        var tagList = [];
        for(var i = 0; i < root.__model.count; ++i) {
            if(root.__model.get(i).title.length && root.__model.get(i).checked)
                tagList[i] = "user/-/label/" + root.__model.get(i).title;
        }
        root.pageItem.service.setItemTags(root.pageItem, tagList);
    }
    onRejected: {
        if(root.busy) {
            root.open();
            root.service.abortSettingItemTags(root.pageItem);
        }
    }

    Connections {
        target: root.pageItem.service
        onSettingItemTagsFinished: {
            if((result == GoogleReaderEnum.ErrNoError)
               || (result == GoogleReaderEnum.ErrAborted)) {
                root.close();
                return;
            }
            root.busy = false;
            if(result == GoogleReaderEnum.ErrNetworkError)
                root.showMessage(qsTr("Network error"));
            else
                root.showMessage(root.failureText);
        }
    }    

    Component {
        id: tagListDelegateComponent
        Item {
            id: tagListDelegate
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.leftMargin: UIConstants.DEFAULT_MARGIN
            anchors.rightMargin: UIConstants.DEFAULT_MARGIN
            height: UIConstants.LIST_ITEM_HEIGHT_SMALL
            Label {
                id: title
                anchors.right: tagSwitch.left
                anchors.rightMargin: UIConstants.LIST_ITEM_SPACING
                anchors.left: parent.left
                anchors.verticalCenter: parent.verticalCenter
                wrapMode: Text.NoWrap
                elide: Text.ElideRight
                font.pixelSize: UIConstants.LIST_TILE_SIZE
                font.weight: Font.Bold
                text: model.title
            }
            Shared.Switch {
                id: tagSwitch
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                checked: model.checked
                onCheckedChanged: {
                    if(tagSwitch.checked != model.checked) {
                        root.__model.setProperty(index, "checked", tagSwitch.checked);
                        root.acceptButton.enabled = true;
                    }
                }
            }
        }
    }

    Component {
        id: tagCloudComponent
        Item {
            id: flickableContainer
            anchors.fill: parent
            anchors.leftMargin: UIConstants.DEFAULT_MARGIN
            anchors.rightMargin: UIConstants.DEFAULT_MARGIN

            ScrollDecorator {
                flickableItem: flickable
            }
            Flickable {
                id: flickable
                anchors.fill: parent
                contentHeight: flowLayout.height
                contentWidth: flowLayout.width
                flickableDirection: Flickable.VerticalFlick
                clip: true
                Connections {
                    target: root
                    onItemsAdded: flowLayout.doLayout();
                }

                Item {
                    id: flowLayout
                    width: flickable.width
                    Repeater {
                        model: root.__model
                        visible: false
                        delegate: Item {
                            id: delegateItem
                            width: tagLabel.paintedWidth + (UIConstants.PADDING_DOUBLE * 2)
                            height: tagLabel.paintedHeight + (UIConstants.PADDING_DOUBLE * 2)
                            Label {
                                id: tagLabel
                                anchors.centerIn: parent
                                text: (model.title.length < 20) ? model.title : (model.title.substr(0, 18) + "...")
                                wrapMode: Text.NoWrap
                                elide: Text.ElideRight
                                font.family: UIConstants.FONT_FAMILY_BOLD
                                font.weight: Font.Black
                                font.pixelSize: UIConstants.FONT_DEFAULT
                                color: model.checked ? UIConstants.HIGHLIGHT_COLOR : "black"
                            }
                            MouseArea {
                                anchors.fill: parent
                                onClicked: {
                                    root.__model.setProperty(index, "checked", !model.checked);
                                    root.acceptButton.enabled = true;
                                }
                            }
                        }
                    }
                    onWidthChanged: doLayout();
                    function doLayout() {
                        var begin = 0;
                        var advanceY = 0;
                        var lineWidth = 0;
                        var itemCount = 0;
                        var spacing = 0;
                        for(var i = 0; i < flowLayout.children.length; ++i) {
                            if(!flowLayout.children[i].visible)
                                continue;
                            var currentWidth = flowLayout.children[i].width;
                            if(((lineWidth + currentWidth) < flowLayout.width)
                                    || (itemCount == 0)) {
                                lineWidth += currentWidth;
                                itemCount++;
                            }
                            else {
                                spacing = (flowLayout.width - lineWidth) / (itemCount + 1);
                                advanceY = positionChildItems(begin, itemCount, spacing, advanceY);
                                itemCount = 1;
                                begin = i;
                                lineWidth = currentWidth;
                            }
                        }
                        if(itemCount > 0) {
                            spacing = (flowLayout.width - lineWidth) / (itemCount + 1);
                            advanceY = positionChildItems(begin, itemCount, spacing, advanceY);
                        }
                        flowLayout.height = advanceY;
                    }
                    function positionChildItems(begin, itemCount, spacing, yPos) {
                        var advanceX = 0;
                        var lowestBottom = 0;
                        for(var i = begin; i < (begin + itemCount); ++i) {
                            if(!flowLayout.children[i].visible)
                                continue;
                            flowLayout.children[i].x = Number(advanceX + spacing);
                            flowLayout.children[i].y = Number(yPos);
                            advanceX = flowLayout.children[i].x + flowLayout.children[i].width;
                            var bottom = (flowLayout.children[i].y + flowLayout.children[i].height);
                            if(bottom > lowestBottom)
                                lowestBottom = bottom;
                        }
                        return lowestBottom;
                    }
                }
            }
        }
    }

    Component {
        id: folderListComponent
        Item {
            id: tagListContainer
            anchors.fill: parent
            Connections {
                target: root
                onItemsAdded: tagListView.positionViewAtBeginning();
            }
            ListView {
                id: tagListView
                anchors.fill: parent
                clip: true
                model: root.__model
                delegate: tagListDelegateComponent
                cacheBuffer: 100 * UIConstants.LIST_ITEM_HEIGHT_SMALL
            }
            ScrollDecorator {
                flickableItem: tagListView
            }
        }
    }

    contentItem: Item {
        id: contentItem
        anchors.fill: parent

        Column {
            id: contentColumn
            anchors.left: parent.left
            anchors.right: parent.right
            anchors.leftMargin: UIConstants.DEFAULT_MARGIN
            anchors.rightMargin: UIConstants.DEFAULT_MARGIN
            spacing: UIConstants.DEFAULT_HALF_MARGIN

            function addNewTag() {
                root.addTag(newTagField.text);
                newTagField.text = "";
            }
            Shared.TextField {
                id: newTagField
                width: parent.width
                placeholderText: (root.pageItem.itemType == GoogleReaderItem.ItFeedItem) ? qsTr("Enter new folder here") : qsTr("Enter new tag here")
                validator: RegExpValidator{regExp: /[^\"\<\>\?\&\/\\\^\,]*/}
                platformSipAttributes: SipAttributes {
                    actionKeyEnabled: newTagButton.enabled
                    actionKeyLabel: qsTr("Add")
                    actionKeyHighlighted: true
                }
                Keys.onReturnPressed: {
                    if(newTagButton.enabled)
                        contentColumn.addNewTag();
                }
            }
            Shared.Button {
                id: newTagButton
                anchors.horizontalCenter: parent.horizontalCenter
                text: (root.pageItem.itemType == GoogleReaderItem.ItFeedItem) ? qsTr("Add new folder") : qsTr("Add new tag")
                enabled: newTagField.text.length
                onClicked: contentColumn.addNewTag();
            }

            Shared.LabeledSeparator {
                text: (root.pageItem.itemType == GoogleReaderItem.ItFeedItem) ? qsTr("Folders") : qsTr("Tags")
            }
        }
        Loader {
            id: contentsLoader
            anchors.top: contentColumn.bottom
            anchors.bottom: parent.bottom
            anchors.left: parent.left
            anchors.right: parent.right
            sourceComponent: (root.pageItem.itemType == GoogleReaderItem.ItFeedItem) ? folderListComponent : tagCloudComponent
        }
    }
}
